package com.example.demo.pdf;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 描述
 *
 * @author: yuy
 */
public class PDFUtils {

    /**
     * https://blog.csdn.net/qq_37654153/article/details/82596727
     * <p>
     * https://www.cnblogs.com/qlqwjy/p/9326468.html
     *
     * @param inputFile     你的PDF文件地址
     * @param outputFile    添加水印后生成PDF存放的地址
     * @param waterMarkName 你的水印
     * @return
     */
    public static boolean waterMark(String inputFile, String outputFile, String waterMarkName) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            //这里的字体设置比较关键，这个设置是支持中文的写法
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte under;
//            Rectangle pageRect = null;
            for (int i = 1; i < total; i++) {
//                pageRect = stamper.getReader().getPageSizeWithRotation(i);
                // 计算水印X,Y坐标
//                float x = pageRect.getWidth()/10;
//                float y = pageRect.getHeight()/10-10;
                // 获得PDF最顶层
                under = stamper.getOverContent(i);
//                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 设置透明度为0.2
                gs.setFillOpacity(0.5f);
                under.setGState(gs);
//                under.restoreState();
                under.beginText();
                under.setFontAndSize(base, 16);
                under.setTextMatrix(200, 500);
                under.setColorFill(BaseColor.LIGHT_GRAY);
                for (int y = 0; y < 2; y++) {
                    for (int x = 0; x < 3; x++) {
                        // 水印文字成45度角倾斜
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, 350 * x, 150+350 * y, 55);
                    }
                }

                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
            }
            stamper.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * https://www.cnblogs.com/qlqwjy/p/9326468.html
     *
     * @param inputFile
     * @param outputFile
     * @param waterMarkName
     */
    public static void waterMark2(String inputFile, String outputFile, String waterMarkName) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            //这里的字体设置比较关键，这个设置是支持中文的写法
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte content;
            PdfGState gs = new PdfGState();
            for (int i = 1; i < total; i++) {
                content = stamper.getOverContent(i);// 在内容上方加水印
                // content = stamper.getUnderContent(i);//在内容下方加水印
                gs.setFillOpacity(0.2f);
//            content.setGState(gs);
                content.beginText();
                content.setColorFill(BaseColor.LIGHT_GRAY);
                content.setFontAndSize(base, 25);
                content.setTextMatrix(70, 200);
                content.showTextAligned(Element.ALIGN_CENTER, waterMarkName, 300, 350, 55);
            /*
              img.setAlignment(Image.LEFT | Image.TEXTWRAP);
              img.setBorder(Image.BOX); img.setBorderWidth(10);
              img.setBorderColor(BaseColor.WHITE); img.scaleToFit(100072);//大小
              img.setRotationDegrees(-30);//旋转
             */
//            content.setColorFill(BaseColor.BLACK);
//            content.setFontAndSize(base, 8);
//            content.showTextAligned(Element.ALIGN_CENTER, "下载时间：" + waterMarkName + "", 300, 10, 0);
                content.endText();
            }
            stamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static  void markPdf(HttpServletResponse response, String inputFile, String markName) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, response.getOutputStream());
            //这里的字体设置比较关键，这个设置是支持中文的写法
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);// 使用系统字体
            int total = reader.getNumberOfPages() + 1;

            PdfContentByte under;
            for (int i = 1; i < total; i++) {
                // 获得PDF最顶层
                under = stamper.getOverContent(i);
//                under.saveState();
                // set Transparency
                PdfGState gs = new PdfGState();
                // 设置透明度为0.2
                gs.setFillOpacity(0.5f);
                under.setGState(gs);
//                under.restoreState();
                under.beginText();
                under.setFontAndSize(base, 18);
                under.setTextMatrix(200, 500);
                under.setColorFill(BaseColor.LIGHT_GRAY);
                for (int y = 0; y < 2; y++) {
                    for (int x = 0; x < 3; x++) {
                        // 水印文字成45度角倾斜
                        under.showTextAligned(Element.ALIGN_LEFT, markName, 350 * x, 150 + 350 * y, 55);
                    }
                }
                // 添加水印文字
                under.endText();
                under.setLineWidth(1f);
                under.stroke();
            }
            stamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        PDFUtils.waterMark("/Users/deck/Desktop/files/yuyang_java.pdf", "/Users/deck/Desktop/files/test11.pdf",
            format.format(new Date()) + "-测试1-11056006");

        PDFUtils.waterMark2("/Users/deck/Desktop/files/yuyang_java.pdf", "/Users/deck/Desktop/files/test2.pdf",
            format.format(new Date()) + "-测试2-11056006");
    }
}
